<template>
  <view class="page page-primary page-grey page-coupon-view has-fixed-footer">
    <page-header theme="colorful"></page-header>
    <view class="page-content">
      <view class="page-statistic">
        <view class="statistic-header-name">
          <fui-text :text="couponData.name" size="36" color="#333" fontWeight="bold"></fui-text>
          <view class="statistic-header-status" :style="couponStatusStyle">{{ COUPON_STATUS[couponData.status].name }}</view>
        </view>
        <view class="statistic-content-list">
          <view class="statistic-content-item">
            <view class="statistic-item-value">
              <fui-text text="满" size="28" color="#666"></fui-text>
              <fui-text :text="couponData.discountRules.split('-')[0]" size="56" :padding="[0, '8rpx']" color="var(--fui-color-primary)" fontWeight="bold"></fui-text>
              <fui-text text="减" :padding="[0, '8rpx']" size="28" color="#666"></fui-text>
              <fui-text :text="couponData.discountRules.split('-')[1]" size="56" color="var(--fui-color-primary)" fontWeight="bold"></fui-text>
            </view>
            <view class="statistic-item-name"><fui-text text="满减门槛及金额" size="24" color="#999"></fui-text></view>
          </view>
          <view class="statistic-content-item">
            <view class="statistic-item-value">
              <fui-text :text="formatValue(couponData.grantNumber || 0)" size="56" color="#3CDB9A" fontWeight="bold"></fui-text>
              <fui-text :text="formatUnit(couponData.grantNumber || 0, '张')" size="28" color="#666"></fui-text>
              <fui-text text="/" :padding="[0, '8rpx']" size="48" color="#999"></fui-text>
              <fui-text :text="formatValue(couponData.issueNumber || 0)" size="56" color="#3CDB9A" fontWeight="bold"></fui-text>
              <fui-text :text="formatUnit(couponData.issueNumber || 0, '张')" size="28" color="#666"></fui-text>
            </view>
            <view class="statistic-item-name"><fui-text text="发行及领取进度" size="24" color="#999"></fui-text></view>
          </view>
        </view>
      </view>
      <view class="coupon-view-content">
        <view class="coupon-view-item">
          <view class="coupon-view-name"><fui-text text="推广人群" size="28" color="#333" fontWeight="bold"></fui-text></view>
          <view class="coupon-view-value"><fui-text :text="COUPON_USER_TYPE[couponData.targetCrowd].name" size="24" color="#666"></fui-text></view>
        </view>
        <view class="coupon-view-item">
          <view class="coupon-view-name"><fui-text text="使用范围" size="28" color="#333" fontWeight="bold"></fui-text></view>
          <view class="coupon-view-value">
            <fui-text :text="COUPON_GOODS_RANGE[couponData.productScope].name" size="24" color="#666"></fui-text>
            <fui-text v-if="couponData.productScope == 32" :text="`（${couponData.checkedCategoryNames}）`" size="24" color="#333"></fui-text>
            <template v-if="couponData.productScope == 33">
              <fui-text v-if="couponData.productScopeIds.indexOf('-1') > -1" text="（全部直供）" size="24" color="#333"></fui-text>
              <fui-text v-else-if="couponData.productScopeIds.indexOf('-2') > -1" text="（全部自营）" size="24" color="#333"></fui-text>
              <fui-text v-else text="查看供应商" :padding="[0, '20rpx']" size="24" color="var(--fui-color-primary)" @click="handleToSuppliers"></fui-text>
            </template>
            <fui-text v-if="couponData.productScope == 72" text="查看商品" :padding="[0, '20rpx']" size="24" color="var(--fui-color-primary)" @click="handleToGoods"></fui-text>
          </view>
        </view>
        <view class="coupon-view-item">
          <view class="coupon-view-name"><fui-text text="可领取时间" size="28" color="#333" fontWeight="bold"></fui-text></view>
          <view class="coupon-view-value"><fui-text :text="`${utils.dateFormatter(couponData.receiveStartTime, 'y-m-d h:i', 2, true)} - ${utils.dateFormatter(couponData.receiveEndTime, 'y-m-d h:i', 2, true)}`" size="24" color="#666"></fui-text></view>
        </view>
        <view class="coupon-view-item">
          <view class="coupon-view-name"><fui-text text="可使用时间" size="28" color="#333" fontWeight="bold"></fui-text></view>
          <view class="coupon-view-value"><fui-text :text="`${utils.dateFormatter(couponData.useStartTime, 'y-m-d h:i', 2, true)} - ${utils.dateFormatter(couponData.useEndTime, 'y-m-d h:i', 2, true)}`" size="24" color="#666"></fui-text></view>
        </view>
        <view class="coupon-view-item">
          <view class="coupon-view-name"><fui-text text="每家限领" size="28" color="#333" fontWeight="bold"></fui-text></view>
          <view class="coupon-view-value"><fui-text :text="`每家限领${couponData.averageLimit}张`" size="24" color="#666"></fui-text></view>
        </view>
      </view>
    </view>
    <view class="page-footer ui-fixed-footer ui-fixed-footer__white">
      <fui-button v-if="couponData.status != 15" text="结束" type="danger" height="78rpx" background="#f95a5a" @click="handleFinish"></fui-button>
      <fui-button v-if="couponData.status != 13" text="查看数据" type="success" height="78rpx" background="var(--fui-color-primary)" @click="handleToStatistic"></fui-button>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, inject } from 'vue'
import { onLoad, onShow } from '@dcloudio/uni-app'
import { useStore } from 'vuex'
import { COUPON_STATUS, COUPON_USER_TYPE, COUPON_GOODS_RANGE } from './consts'
import { formatValue, formatUnit } from '@/utils/tools'
import utils from '@/components/firstui/fui-utils'
import pageHeader from '@/components/header'
import couponApi from '@/api/coupon'

const store = useStore()
const tab = inject('$tab')
const modal = inject('$modal')

const couponId = ref('')
const categoryData = ref([])
onLoad(option => {
  couponId.value = option.couponId
  categoryData.value = store.getters.productCategoryFormatting
})

onShow(() => {
  getCouponDetail()
})

// 优惠券详情
const couponData = ref({
  status: 11,
  targetCrowd: 21,
  productScope: 31,
  discountRules: '1-1'
})
const couponStatusStyle = computed(() => {
  return { 
    background: COUPON_STATUS[couponData.value.status].background, 
    color: COUPON_STATUS[couponData.value.status].color
  }
})
const getCouponDetail = () => {
  modal.loading('加载中...')
  try {
    couponApi.getCouponDetail(couponId.value).then(res => {
      modal.closeLoading()
      if (res.code === 0 && res.data) {
        couponData.value = res.data
        if (couponData.value.productScope == 32) {
          const checkedCategoryArr = categoryData.value.filter(item => couponData.value.productScopeIds.indexOf(item.id + '') > -1)
          const checkedCategoryNames = checkedCategoryArr.map(item => item.name)
          couponData.value.checkedCategoryNames = checkedCategoryNames.join(',')
        }
      } else {
        modal.msgError(res.msg)
      }
    })
  } catch(err){
    modal.closeLoading()
    modal.msgError(err)
  }
}

// 结束
const handleFinish = () => {
  modal.confirm('结束后，该优惠券将无法领取，已领取的优惠券在可用的时间内正常使用，确定结束该优惠券吗？').then(() => {
    couponApi.updateCouponStatus({
      id: couponId.value,
      status: 15
    }).then((res) => {
      if (res.code === 0) {
        modal.msg(`【${couponData.value.name}】已结束！`)
        setTimeout(() => {
          tab.navigateBack()
        }, 1000)
      } else {
        modal.msgError(res.msg || `【${couponData.value.name}】结束失败！`)
      }
    }).catch(err => {
      modal.msgError(err.msg || err || `【${couponData.value.name}】结束失败！`)
    })
  })
}

// 查看供应商
const handleToSuppliers = () => {
  tab.navigateTo(`/pages/coupon/supplier?supplierIds=${couponData.value.productScopeIds}`)
}

// 查看商品
const handleToGoods = () => {
  tab.navigateTo(`/pages/coupon/goods?spuIds=${couponData.value.productScopeIds}`)
}

// 查看数据
const handleToStatistic = () => {
  tab.navigateTo(`/pages/coupon/statistic?couponId=${couponId.value}`)
}
</script>

<style lang="scss" scoped>
.page-coupon-view {
  .page-statistic {
    width: 100%;
    background: #ffffff;
    padding: 36rpx;
    box-sizing: border-box;
    border-radius: 16rpx;
    .statistic-header-name {
      display: flex;
      align-items: center;
      margin-bottom: 32rpx;
      .statistic-header-status {
        flex: 0 0 92rpx;
        display: inline-block;
        width: 92rpx;
        height: 32rpx;
        border-radius: 4rpx;
        margin-left: 18rpx;
        text-align: center;
        line-height: 32rpx;
        font-size: 20rpx;
        font-weight: bold;
      }
    }
    .statistic-content-list {
      display: flex;
      justify-content: space-between;
      align-items: center;
      .statistic-content-item {
        flex: 0 0 50%;
        width: 50%;
        text-align: center;
        &:not(:last-child) {
          position: relative;
          &:after {
            position: absolute;
            top: 50%;
            right: -1rpx;
            content: '';
            width: 2rpx;
            height: 64rpx;
            background-color: #E6E2E2;
            margin-top: -32rpx;
          }
        }
        .statistic-item-name {
          margin: 10rpx 0;
        }
      }
    }
  }
  .coupon-view-content {
    min-height: 70vh;
    background-color: #fff;
    margin: 30rpx -36rpx 0;
    padding: 36rpx;
    .coupon-view-item {
      margin-bottom: 36rpx;
      .coupon-view-name {
        margin-bottom: 16rpx;
        &::before {
          display: inline-block;
          content: '';
          width: 22rpx;
          height: 22rpx;
          border: 6rpx solid var(--fui-color-primary);
          border-radius: 50%;
          box-sizing: border-box;
          margin-right: 16rpx;
        }
      }
      .coupon-view-value {
        padding-left: 38rpx;
      }
    }
  }
  .page-footer {
    display: flex;
    .fui-button__wrap {
      flex: 1;
      margin: 0 10rpx !important;
    }
  }
}
</style>